/*
 * $Header: $
 * $Id$
 *
 * Copyright (c) 2011, Mike DePhillips. All Rights Reserved.
 * This code may not be used without the express written permission
 * of the copyright holder, Mike DePhillips.
 */

package com.facebook.bannermaker.android;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import com.facbook.bannermaker.android.util.ActivityUtil;
import com.facebook.android.Facebook;
import com.facebook.bannermaker.android.util.AppConstants;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

/**
 * Activity for browsing inbox and acquiring tasks
 *
 * @author Michael DePhillips
 * 
 */
public class LoginActivity extends Activity {

    private static final String APP_ID = "212393005452204";
    public Facebook m_facebook = new Facebook(APP_ID);
    protected String m_accessToken = null;
    protected String m_name = null;
    protected String m_id = null;
    
    private GoogleAnalyticsTracker tracker;

    private static final int IMAGE_PICK = 1234;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);  
        
        tracker = GoogleAnalyticsTracker.getInstance();

        // Start the tracker in manual dispatch mode...
        tracker.startNewSession(AppConstants.GOOGLE_ANALYTICS_CODE, this);
        
        tracker.trackPageView("/Home");

        tracker.dispatch();
        
        // make banner
        createAndShowBanner();     
    }    

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // retrieve image from cursor
        if( requestCode == IMAGE_PICK ) {
            if(resultCode == RESULT_OK){  

                Uri selectedImageUri = data.getData();

                //OI FILE Manager
                String filemanagerstring = selectedImageUri.getPath();

                //MEDIA GALLERY
                String selectedImagePath = getPath(selectedImageUri);

                String filePath = null;

                //NOW WE HAVE OUR WANTED STRING
                if(selectedImagePath!=null) {
                    filePath = selectedImagePath;
                }
                else {
                    filePath = filemanagerstring;
                }

                // check if this the first time using the app, if it is, load the tutorial activity
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                boolean first_time_app_use = prefs.getBoolean(AppConstants.FIRST_TIME_USE, true);                                
         
                if( !first_time_app_use ) {
	                // otherwise,send data to the banner maker activity
	                ActivityUtil.loadMakeBannerFromMemoryActivity(this, m_id, filePath);
                }
                else {
                	 // otherwise,send data to the banner maker activity
	                ActivityUtil.loadMakeBannerTutorialActivity(this, m_id, filePath);
                }
            }
        }
    }

    /**
     * Gets a file path from a curosr that is returned from gallery intent
     * @param uri
     * @return
     */
    private String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if(cursor!=null)
        {
            //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else return null;
    }

    /**
     * Create a banner by chopping a bitmap into 5 pieces
     */
    private void createAndShowBanner() {       

        Bitmap resource;
        // create bitmap from resource
        resource = BitmapFactory.decodeResource(getResources(), R.drawable.facebook_banner_logo_large);
        ImageView images[] = new ImageView[5];                      

        final int BANNER_WIDTH = resource.getWidth()/5;
        final int BANNER_HEIGHT = resource.getHeight();

        // load banner images from xml
        images[0] = (ImageView)findViewById(R.id.img_banner1);
        images[1] = (ImageView)findViewById(R.id.img_banner2);
        images[2] = (ImageView)findViewById(R.id.img_banner3);
        images[3] = (ImageView)findViewById(R.id.img_banner4);
        images[4] = (ImageView)findViewById(R.id.img_banner5);
        
        // transfer the bitmaps to the xml images
        for(int i = 0; i < 5; i++) {            
            images[i].setImageBitmap(Bitmap.createBitmap(resource, i*BANNER_WIDTH, 0, BANNER_WIDTH, BANNER_HEIGHT));            
        }

        // recycle non-used bitmap resource
        resource.recycle();
        resource = null;
    }

    /**
     * Create options menu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return ActivityUtil.createGlobalOptionsMenu(this, menu);
    }

    /**
     * Control flow for options menu selection
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return ActivityUtil.onGlobalOptionsItemSelected(this, item);
    }   

    /**
     * User clicked create banner from template button
     * @param v
     */
    public void onMakeBannerFromTemplateClicked(View v) {
    	
    	// register the user clicked the button
        tracker.trackEvent(
        		"Button",  // Category
                "Click",  // Action
                "Template", // Label
                20);       // Value
    	
        ActivityUtil.loadMakeBannerFromTemplateActivity(this, m_id);
    }

    @Override
    protected void onDestroy() {
      super.onDestroy();
      // Stop the tracker when it is no longer needed.
      tracker.stopSession();
    }
    
    /**
     * Loads Banner from Memory Activity
     * @param v
     */
    public void onMakeBannerFromMemoryClicked(View v) {
    	
    	// register the user clicked the button
        tracker.trackEvent(
        		"Button",  // Category
                "Click",  // Action
                "Memory", // Label
                10);       // Value
    	
        // open gallery activity to choose image
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_PICK); 
        //ActivityUtil.loadMakeBannerFromMemoryActivity(this, m_id);
    }

    /**
     * Load Help Menu Activity when help button is clicked
     * @param v
     */
    public void onHelpButtonClicked(View v) {    	    	
        ActivityUtil.loadHelpActivity(this);
    }
}